package com.zanha.javacmsframework.controller.admin;
import static act.controller.Controller.Util.renderTemplate;
import javax.inject.Inject;
import javax.validation.Valid;

import com.zanha.javacmsframework.logic.AdminsLogic;
import org.osgl.http.H;
import org.osgl.mvc.annotation.Before;
import org.osgl.mvc.annotation.GetAction;
import org.osgl.mvc.annotation.PostAction;
import com.alibaba.fastjson.JSONObject;
import com.zanha.javacmsframework.model.authority.AdminsModel;

import act.app.ActionContext;
import act.controller.Controller.Util;
import act.db.ebean.EbeanDao;
import act.view.RenderAny;

/**
 * 登录
 * @author 粽子
 */
public class Login{		
	@Inject
    private H.Session session;
	
	@Inject
    private EbeanDao<Integer,AdminsModel> adminsDao;
	
	/**
	 * 如果查看登陆页面，系统本省已经登录了，就直接进入后台了
	 * @author 粽子
	 */
	@Before
	public void checkLogin(){
		if(session.get("admin_username") != null && session.get("adminid") != null) {        	
			throw Util.redirect("Index.index");
        }
	}
	
	/**
	 * 登录界面
	 * @return
	 * @author 粽子
	 */
	@GetAction(value={"/admin/Login/index","/admin/Login"})
	public RenderAny index(){			
		return renderTemplate("/admin/Login/index.html");
	}	
	
	/**
	 * 登录逻辑
	 * @param logindata
	 * @return
	 * @author 粽子
	 */
	@PostAction("/admin/Login/loginHandler")
	public JSONObject loginHandler(@Valid AdminsModel logindata,ActionContext context){		
		JSONObject result = new JSONObject();
		if(context.hasViolation()){
			result.put("errcode", 1);
            result.put("msg",context.violationMessage());
            return result;
		}
				
		String username = logindata.getUsername().trim();
		String password = logindata.getPassword().trim();		
		if(username == null || password == null || username.isEmpty() || password.isEmpty()){
			result.put("errcode", 1);
            result.put("msg", "用户名、密码不能为空！");
            return result;
		}						
		AdminsLogic adminsLogic = new AdminsLogic();
		AdminsModel admin = adminsDao.findOneBy("username",username);
		if(false == adminsLogic.checkPassword(admin.getPassword(),adminsLogic.encodePassword(password,admin.getSafekey()))){
			result.put("errcode", 1);
            result.put("msg", "用户名或密码不对！");
		}else{
			session.put("admin_username",admin.getUsername());
            session.put("adminid",admin.getAdminid());            
            result.put("errcode", 0);
            result.put("msg", "登陆成功正在为你跳转！");
		}
		return result;
	}		
}